package com.ecommerce.chat.controller;

import com.ecommerce.chat.dto.ChatRequest;
import com.ecommerce.chat.dto.ChatResponse;
import com.ecommerce.chat.service.AsyncTaskManager;
import com.ecommerce.chat.service.ChatService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 异步聊天控制器
 * 专为小程序设计的异步聊天接口，解决小程序不支持SSE流式接口的问题
 * 
 * 接口设计原则：
 * 1. 响应时间控制在200ms内
 * 2. 返回数据结构扁平化，前端即用
 * 3. 提供明确的状态码和错误信息
 * 4. 支持任务状态实时查询
 * 
 * @author AI客服系统
 */
@Slf4j
@RestController
@RequestMapping("/api/chat/async")
@CrossOrigin(origins = "*")
public class AsyncChatController {
    
    @Autowired
    private ChatService chatService;
    
    @Autowired
    private AsyncTaskManager taskManager;
    
    /**
     * 异步任务提交响应
     */
    @Data
    public static class AsyncTaskResponse {
        private String taskId;
        private String status;
        private String message;
        private LocalDateTime createTime;
        private Long estimatedWaitTime; // 预估等待时间（秒）
        
        public static AsyncTaskResponse success(String taskId) {
            AsyncTaskResponse response = new AsyncTaskResponse();
            response.setTaskId(taskId);
            response.setStatus("submitted");
            response.setMessage("任务已提交，请使用taskId查询处理状态");
            response.setCreateTime(LocalDateTime.now());
            response.setEstimatedWaitTime(5L); // 预估5秒内完成
            return response;
        }
        
        public static AsyncTaskResponse error(String message) {
            AsyncTaskResponse response = new AsyncTaskResponse();
            response.setStatus("error");
            response.setMessage(message);
            response.setCreateTime(LocalDateTime.now());
            return response;
        }
    }
    
    /**
     * 任务状态响应
     */
    @Data
    public static class TaskStatusResponse {
        private String taskId;
        private String status;
        private String statusDesc;
        private String message;
        private LocalDateTime updateTime;
        private Integer progress; // 进度百分比 0-100
        private Boolean completed;
        private Boolean hasResult;
        
        public static TaskStatusResponse create(String taskId, AsyncTaskManager.TaskStatus status) {
            TaskStatusResponse response = new TaskStatusResponse();
            response.setTaskId(taskId);
            response.setStatus(status.getCode());
            response.setStatusDesc(status.getDescription());
            response.setUpdateTime(LocalDateTime.now());
            response.setCompleted(status == AsyncTaskManager.TaskStatus.COMPLETED || 
                                status == AsyncTaskManager.TaskStatus.FAILED);
            response.setHasResult(status == AsyncTaskManager.TaskStatus.COMPLETED);
            
            // 设置进度和消息
            switch (status) {
                case PENDING:
                    response.setProgress(0);
                    response.setMessage("任务排队中，请稍候...");
                    break;
                case PROCESSING:
                    response.setProgress(50);
                    response.setMessage("AI正在思考中，请稍候...");
                    break;
                case COMPLETED:
                    response.setProgress(100);
                    response.setMessage("处理完成，可获取结果");
                    break;
                case FAILED:
                    response.setProgress(100);
                    response.setMessage("处理失败，请重试");
                    break;
                case EXPIRED:
                    response.setProgress(100);
                    response.setMessage("任务已过期");
                    break;
            }
            
            return response;
        }
        
        public static TaskStatusResponse notFound(String taskId) {
            TaskStatusResponse response = new TaskStatusResponse();
            response.setTaskId(taskId);
            response.setStatus("not_found");
            response.setStatusDesc("任务不存在");
            response.setMessage("任务ID不存在或已过期");
            response.setUpdateTime(LocalDateTime.now());
            response.setCompleted(true);
            response.setHasResult(false);
            response.setProgress(0);
            return response;
        }
    }
    
    /**
     * 任务结果响应
     */
    @Data
    public static class TaskResultResponse {
        private String taskId;
        private String status;
        private String reply;
        private String sessionId;
        private LocalDateTime completeTime;
        private String errorMessage;
        private Map<String, Object> metadata;
        
        public static TaskResultResponse success(String taskId, ChatResponse chatResponse) {
            TaskResultResponse response = new TaskResultResponse();
            response.setTaskId(taskId);
            response.setStatus("success");
            response.setReply(chatResponse.getReply());
            response.setSessionId(chatResponse.getSessionId());
            response.setCompleteTime(LocalDateTime.now());
            
            // 添加元数据
            Map<String, Object> metadata = new HashMap<>();
            metadata.put("replyLength", chatResponse.getReply() != null ? chatResponse.getReply().length() : 0);
            metadata.put("hasSession", StringUtils.hasText(chatResponse.getSessionId()));
            response.setMetadata(metadata);
            
            return response;
        }
        
        public static TaskResultResponse error(String taskId, String errorMessage) {
            TaskResultResponse response = new TaskResultResponse();
            response.setTaskId(taskId);
            response.setStatus("error");
            response.setErrorMessage(errorMessage);
            response.setCompleteTime(LocalDateTime.now());
            return response;
        }
        
        public static TaskResultResponse notReady(String taskId, String currentStatus) {
            TaskResultResponse response = new TaskResultResponse();
            response.setTaskId(taskId);
            response.setStatus("not_ready");
            response.setErrorMessage("任务尚未完成，当前状态: " + currentStatus);
            return response;
        }
    }
    
    /**
     * 提交异步聊天任务
     * 
     * @param request 聊天请求
     * @return 任务提交响应
     */
    @PostMapping
    public ResponseEntity<AsyncTaskResponse> submitTask(@RequestBody ChatRequest request) {
        long startTime = System.currentTimeMillis();
        
        try {
            // 参数验证
            if (request == null || !StringUtils.hasText(request.getMessage())) {
                return ResponseEntity.badRequest()
                    .body(AsyncTaskResponse.error("消息内容不能为空"));
            }
            
            // 消息长度限制
            if (request.getMessage().length() > 2000) {
                return ResponseEntity.badRequest()
                    .body(AsyncTaskResponse.error("消息内容过长，请控制在2000字符以内"));
            }
            
            // 创建异步任务
            String taskId = taskManager.createTask(request);
            
            // 异步执行聊天任务
            CompletableFuture<ChatResponse> future = chatService.chatAsync(request);
            taskManager.setTaskFuture(taskId, future);
            
            // 设置任务状态为处理中
            taskManager.updateTaskStatus(taskId, AsyncTaskManager.TaskStatus.PROCESSING);
            
            // 异步处理结果
            future.whenComplete((result, throwable) -> {
                if (throwable != null) {
                    taskManager.setTaskError(taskId, throwable.getMessage());
                } else {
                    taskManager.setTaskResult(taskId, result);
                }
            });
            
            long responseTime = System.currentTimeMillis() - startTime;
            log.info("异步任务提交成功: {}, 响应时间: {}ms", taskId, responseTime);
            
            return ResponseEntity.ok(AsyncTaskResponse.success(taskId));
            
        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("异步任务提交失败, 响应时间: {}ms", responseTime, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(AsyncTaskResponse.error("系统繁忙，请稍后重试"));
        }
    }
    
    /**
     * 查询任务状态
     * 
     * @param taskId 任务ID
     * @return 任务状态响应
     */
    @GetMapping("/{taskId}/status")
    public ResponseEntity<TaskStatusResponse> getTaskStatus(@PathVariable String taskId) {
        long startTime = System.currentTimeMillis();
        
        try {
            if (!StringUtils.hasText(taskId)) {
                return ResponseEntity.badRequest()
                    .body(TaskStatusResponse.notFound(taskId));
            }
            
            AsyncTaskManager.TaskStatus status = taskManager.getTaskStatus(taskId);
            if (status == null) {
                return ResponseEntity.notFound().build();
            }
            
            long responseTime = System.currentTimeMillis() - startTime;
            log.debug("查询任务状态: {}, 状态: {}, 响应时间: {}ms", taskId, status.getCode(), responseTime);
            
            return ResponseEntity.ok(TaskStatusResponse.create(taskId, status));
            
        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("查询任务状态失败: {}, 响应时间: {}ms", taskId, responseTime, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(TaskStatusResponse.notFound(taskId));
        }
    }
    
    /**
     * 获取任务结果
     * 
     * @param taskId 任务ID
     * @return 任务结果响应
     */
    @GetMapping("/{taskId}/result")
    public ResponseEntity<TaskResultResponse> getTaskResult(@PathVariable String taskId) {
        long startTime = System.currentTimeMillis();
        
        try {
            if (!StringUtils.hasText(taskId)) {
                return ResponseEntity.badRequest()
                    .body(TaskResultResponse.error(taskId, "任务ID不能为空"));
            }
            
            AsyncTaskManager.TaskStatus status = taskManager.getTaskStatus(taskId);
            if (status == null) {
                return ResponseEntity.notFound().build();
            }
            
            // 检查任务状态
            if (status == AsyncTaskManager.TaskStatus.COMPLETED) {
                ChatResponse result = taskManager.getTaskResult(taskId);
                if (result != null) {
                    long responseTime = System.currentTimeMillis() - startTime;
                    log.info("获取任务结果成功: {}, 响应时间: {}ms", taskId, responseTime);
                    return ResponseEntity.ok(TaskResultResponse.success(taskId, result));
                }
            } else if (status == AsyncTaskManager.TaskStatus.FAILED) {
                String errorMessage = taskManager.getTaskError(taskId);
                return ResponseEntity.ok(TaskResultResponse.error(taskId, errorMessage));
            }
            
            // 任务尚未完成
            return ResponseEntity.ok(TaskResultResponse.notReady(taskId, status.getDescription()));
            
        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("获取任务结果失败: {}, 响应时间: {}ms", taskId, responseTime, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(TaskResultResponse.error(taskId, "系统繁忙，请稍后重试"));
        }
    }
    
    /**
     * 取消任务
     * 
     * @param taskId 任务ID
     * @return 操作结果
     */
    @DeleteMapping("/{taskId}")
    public ResponseEntity<Map<String, Object>> cancelTask(@PathVariable String taskId) {
        long startTime = System.currentTimeMillis();
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (!taskManager.taskExists(taskId)) {
                response.put("success", false);
                response.put("message", "任务不存在");
                return ResponseEntity.notFound().build();
            }
            
            taskManager.removeTask(taskId);
            
            long responseTime = System.currentTimeMillis() - startTime;
            log.info("取消任务成功: {}, 响应时间: {}ms", taskId, responseTime);
            
            response.put("success", true);
            response.put("message", "任务已取消");
            response.put("taskId", taskId);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("取消任务失败: {}, 响应时间: {}ms", taskId, responseTime, e);
            
            response.put("success", false);
            response.put("message", "取消任务失败");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    
    /**
     * 获取系统状态
     * 
     * @return 系统状态信息
     */
    @GetMapping("/system/status")
    public ResponseEntity<Map<String, Object>> getSystemStatus() {
        Map<String, Object> status = new HashMap<>();
        
        try {
            status.put("status", "healthy");
            status.put("currentTasks", taskManager.getTaskCount());
            status.put("timestamp", LocalDateTime.now());
            status.put("version", "1.0.0");
            status.put("description", "小程序异步聊天接口");
            
            return ResponseEntity.ok(status);
            
        } catch (Exception e) {
            log.error("获取系统状态失败", e);
            status.put("status", "error");
            status.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(status);
        }
    }
}